<template>
  <NSpace vertical>
    <n-radio-group v-model:value="data_mode" name="data_mode">
      <n-radio-button 
        v-for="mode in data_modes" 
        :key="mode.value" 
        :value="mode.value" 
        :label="mode.label" 
      />
    </n-radio-group>
    <n-radio-group v-model:value="show_mode" name="show_modes">
      <n-radio-button 
        v-for="mode in show_modes" 
        :key="mode.value" 
        :value="mode.value" 
        :label="mode.label" 
      />
    </n-radio-group>
    <v-chart 
      :key="refreshKey" 
      :option="option" 
      autoresize
      style="background-color: #66ccff33; width: 100%; height: 600px; touch-action: none; overscroll-behavior: none; user-select: none;" 
    />
  </NSpace>
</template>

<script setup>
import { NRadioGroup, NRadioButton, NSpace } from 'naive-ui'
import { computed, ref, watch } from 'vue'
import { use, registerMap } from "echarts/core"
import VChart from "vue-echarts"
import chinaMap from "@/api/getChinaMap"
import { MapChart, BarChart } from 'echarts/charts'
import { 
  TitleComponent, 
  VisualMapComponent, 
  TooltipComponent, 
  GridComponent, 
  DataZoomComponent 
} from 'echarts/components'
import { UniversalTransition } from 'echarts/features'
import { CanvasRenderer } from 'echarts/renderers'

import {
  getProvinceAdmission,
  getCityAdmission,
  getInternationalAdmission
} from "@/api/admission"

import convertProvince from "../tools/convertProvince"

// 注册ECharts组件
use([
  TitleComponent, 
  VisualMapComponent,
  MapChart,
  BarChart,
  CanvasRenderer,
  UniversalTransition, 
  TooltipComponent, 
  GridComponent, 
  DataZoomComponent
])

const refreshKey = ref(0)

// 注册中国地图
chinaMap.then((res) => {
  registerMap("china", res.data)
  refreshKey.value++
}).catch((err) => {
  console.error("Error loading China map data:", err)
  registerMap("china", { type: "FeatureCollection", features: [] })
  refreshKey.value++
})

// 显示模式配置
const show_mode = ref('map')
const show_modes = ref([
  { label: '地图模式', value: 'map' },
  { label: '数据视图', value: 'bar' }
])
const show_mode_label = computed(() => {
  return show_modes.value.find(m => m.value === show_mode.value)?.label || ''
})

// 数据模式配置
const data_mode = ref('province')
const data_modes = ref([
  { label: '省份招生', value: 'province' },
  { label: '城市招生', value: 'city' },
  { label: '国际招生', value: 'international' }
])
const data_mode_label = computed(() => {
  return data_modes.value.find(m => m.value === data_mode.value)?.label || ''
})

// 招生数据
const admission_data = ref([])

// 当前显示数据
const current_data = computed(() => {
  return admission_data.value.filter(item => item && item.name && item.value !== undefined)
})

// API调用函数
const fetchData = async () => {
  try {
    let response
    switch (data_mode.value) {
      case 'province':
        response = await getProvinceAdmission()
        break
      case 'city':
        response = await getCityAdmission()
        break
      case 'international':
        response = await getInternationalAdmission()
        break
      default:
        response = await getProvinceAdmission()
    }
    
    const apiData = response.data.data || []
    
    // 处理API返回的数据
    // API返回格式: [{"province":"四川","city":"成都","plannedNumber":192,"actualNumber":204,"completionRate":106.25}, ...]
    const processedData = apiData.map(item => {
      if (!item || !item.province) return null
      
      if (data_mode.value === 'city') {
        // 城市数据使用省份+城市作为名称
        return {
          name: `${convertProvince(item.province)}-${item.city || '未知城市'}`,
          value: item.plannedNumber || 0,
          actualNumber: item.actualNumber || 0,
          completionRate: item.completionRate || 0
        }
      } else {
        // 省份和国际数据使用省份全称作为名称
        return {
          name: convertProvince(item.province),
          value: item.plannedNumber || 0,
          actualNumber: item.actualNumber || 0,
          completionRate: item.completionRate || 0
        }
      }
    }).filter(item => item !== null) // 过滤掉无效数据
    
    admission_data.value = processedData
  } catch (error) {
    console.error('获取数据失败:', error)
    // 可以在这里添加错误提示
    admission_data.value = [] // 出错时设置为空数组
  }
}

// 监听数据模式变化
watch(
  data_mode,
  async (mode) => {
    await fetchData()
  },
  { immediate: true }   // 首次自动执行一次
)

// 地图配置
const option_map = computed(() => {
  const maxValue = Math.max(...current_data.value.map(item => item.value), 1) // 确保最小值为1
  
  return {
    title: {
      text: data_mode_label.value + " - " + show_mode_label.value,
      left: 'center',
      top: 0
    },
    tooltip: {
      trigger: 'item',
      formatter: params => {
        const item = current_data.value.find(d => d.name === params.name)
        if (item) {
          const total = current_data.value.reduce((sum, d) => sum + d.value, 0)
          const percentage = total > 0 ? (item.value / total * 100).toFixed(1) : '0.0'
          return `${params.name}<br/>计划招生: ${item.value}人<br/>实际招生: ${item.actualNumber}人<br/>完成率: ${item.completionRate}%<br/>占比: ${percentage}%`
        }
        return `${params.name}<br/>招生人数: ${params.value}人`
      },
      backgroundColor: 'rgba(0,0,0,0.7)',
      textStyle: { color: '#fff' }
    },
    visualMap: {
      left: 'right',
      min: 0,
      max: maxValue,
      inRange: {
        color: ['#ffffff', '#65CDF0', '#1E90FF', '#4169E1']
      },
      text: ['高', '低'],
      calculable: true
    },
    series: [{
      id: 'admission',
      type: 'map',
      roam: true,
      scaleLimit: {
        min: 1,
        max: 3
      },
      map: 'china',
      animationDurationUpdate: 1000,
      universalTransition: true,
      data: current_data.value,
      emphasis: {
        itemStyle: {
          areaColor: '#FFA500'
        }
      }
    }]
  }
})

// 柱状图配置
const option_bar = computed(() => {
  const sortedData = [...current_data.value].sort((a, b) => b.value - a.value)
  
  return {
    title: {
      text: data_mode_label.value + " - " + show_mode_label.value,
      left: 'center',
      top: 0
    },
    tooltip: {
      trigger: 'item',
      formatter: params => {
        const item = sortedData[params.dataIndex]
        if (item) {
          const total = current_data.value.reduce((sum, d) => sum + d.value, 0)
          const percentage = total > 0 ? (item.value / total * 100).toFixed(1) : '0.0'
          return `${item.name}<br/>计划招生: ${item.value}人<br/>实际招生: ${item.actualNumber}人<br/>完成率: ${item.completionRate}%<br/>占比: ${percentage}%`
        }
        return `${params.name}<br/>招生人数: ${params.value}人`
      },
      backgroundColor: 'rgba(0,0,0,0.7)',
      textStyle: { color: '#fff' }
    },
    grid: [
      { left: '120', top: '7%', width: '60%', height: '80%' },
    ],
    xAxis: {
      type: 'value'
    },
    yAxis: {
      type: 'category',
      axisLabel: {
        rotate: 0,
        hideOverlap: false,
      },
      data: sortedData.map(item => item.name)
    },
    dataZoom: [
      {
        type: 'slider',
        show: true,
        yAxisIndex: [0],
        right: '0%',
        start: 0,
        end: 100
      },
      {
        type: 'inside',
        yAxisIndex: [0],
        start: 29,
        end: 36
      }
    ],
    animationDurationUpdate: 1000,
    series: [{
      type: 'bar',
      id: 'admission',
      data: sortedData.map(item => item.value),
      universalTransition: true
    }]
  }
})

// 组合选项
const option = computed(() => {
  if (show_mode.value === 'map') {
    return option_map.value;
  } else if (show_mode.value === 'bar') {
    return option_bar.value;
  }
  return option_map.value;
})
</script>

<style scoped>
/* 保持模块一原有样式不变 */
</style>